<template>
  <Dialog
    v-model="dialogVisible"
    :maxHeight="'800px'"
    width="80%"
    title="选择商品"
    :before-close="() => closeDialog()"
  >
    <!--    顶部查询项-->
    <el-form :model="form" inline>
      <el-form-item :label="t('product.cname')">
        <el-input
          v-model="form.cname"
          clearable
          :placeholder="t('product.cname')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('product.abbr')">
        <el-input
          v-model="form.abbr"
          clearable
          :placeholder="t('product.abbr')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('product.brand')">
        <el-select
          v-model="form.brand"
          filterable
          :placeholder="t('product.brand')"
          clearable
          style="width: 250px"
        >
          <el-option
            v-for="item in brandList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="算法">
        <el-select
          v-model="form.algorithm"
          filterable
          placeholder="算法"
          clearable
          style="width: 250px"
        >
          <el-option
            v-for="item in algorithmList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('product.model')">
        <el-select
          v-model="form.model"
          :placeholder="t('product.model')"
          clearable
          style="width: 250px"
        >
          <el-option
            v-for="item in modelList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="'类型'">
        <el-select v-model="form.type" :placeholder="'类型'" clearable style="width: 250px">
          <el-option
            v-for="item in typeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="getList">查询</el-button>
        <el-button icon="Refresh" @click="reset(true)">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格主体 -->
    <el-table
      class="m-t-10px"
      :data="dataList"
      highlight-current-row
      stripe
      border
      ref="tableRef"
      v-loading="tableLoading"
      row-key="id"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center' }"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column
        type="selection"
        :selectable="selectable"
        :reserve-selection="true"
        width="55"
      /> -->
      <el-table-column
        type="selection"
        :selectable="isSelectable"
        :reserve-selection="true"
        width="55"
      />
      <el-table-column
        :label="t('product.id')"
        prop="id"
        min-width="60"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('product.cname')"
        prop="cname"
        :width="calculateColumnWidth(dataList, 'cname')"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('product.abbr')"
        prop="abbr"
        :width="calculateColumnWidth(dataList, 'abbr')"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('product.sku')"
        prop="sku"
        :width="calculateColumnWidth(dataList, 'sku')"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('product.code')"
        prop="code"
        :width="calculateColumnWidth(dataList, 'code')"
        :show-overflow-tooltip="true"
      />
      <el-table-column :label="t('product.brand')" min-width="150" :show-overflow-tooltip="true">
        <template #default="{ row }">
          {{ useEnumeratePicker(brandList, row.brand) }}
        </template>
      </el-table-column>

      <el-table-column
        :label="t('product.algorithm')"
        min-width="150"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          {{ useEnumeratePicker(algorithmList, row.algorithm) }}
        </template>
      </el-table-column>

      <el-table-column :label="t('product.type')" min-width="150" :show-overflow-tooltip="true">
        <template #default="{ row }">
          {{ useEnumeratePicker(typeList, row.type) }}
        </template>
      </el-table-column>

      <el-table-column
        :label="t('product.style_code')"
        prop="style_code"
        :width="calculateColumnWidth(dataList, 'style_code')"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('product.condition')"
        prop="condition"
        min-width="150"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          {{ row.condition === 1 ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('product.hashrate')"
        prop="hashrate"
        :width="calculateColumnWidth(dataList, 'hashrate')"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('product.computing_unit')"
        prop="computing_unit"
        :width="calculateColumnWidth(dataList, 'computing_unit')"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('product.power')"
        prop="power"
        :width="calculateColumnWidth(dataList, 'power')"
        :show-overflow-tooltip="true"
      />
    </el-table>
    <!--    分页-->
    <Pagination
      :total="paginationTotal"
      v-model:page="form.pageIndex"
      v-model:limit="form.pageSize"
      @pagination="getList"
    />
    <template #footer>
      <el-button class="m-r-4" @click="closeDialog"
        >{{ t('system.parameterConfig.cancel') }}
      </el-button>
      <el-button type="primary" @click="submit">{{ t('wholesalOrder.add') }}</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import Pagination from '@/components/Pagination/index.vue'
import { getGoodsEnumApi, getListApi } from '@/api/product'
import { useEnumeratePicker } from '@/utils'
import { Dialog } from '@/components/Dialog'
import { ElMessage } from 'element-plus'
import { calculateColumnWidth } from '@/utils'

const emit = defineEmits(['exposeMultipleData'])
const { t } = useI18n()
const tableRef = ref()

const props = withDefaults(defineProps<{ multiple?: boolean }>(), {
  multiple: false
})

const isReset = ref<boolean>(false)
const dialogVisible = ref<boolean>(false)
const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const multipleSelection = ref<any[]>([])
const selectionPak = ref<any[]>([])

const paginationTotal = ref<number>(0)
// 存储禁用行的id
const disabledRows = ref(new Set())

// 判断行是否可选
const isSelectable = (row: Record<string, any>) => {
  return !disabledRows.value.has(row.id)
}

const form = ref<Record<string, any>>({
  cname: '',
  abbr: '',
  brand: '',
  type: '',
  algorithm: '',
  model: '',
  pageIndex: 1,
  pageSize: 15
})
const brandList = ref<Array<Record<string, any>>>([])
const modelList = ref<Array<Record<string, any>>>([])
const algorithmList = ref<Array<Record<string, any>>>([])
const typeList = ref<Array<Record<string, any>>>([
  {
    label: '商品',
    value: 1
  },
  {
    label: '配件',
    value: 2
  }
])

//格式化时间
const changeTime = (e: Date[]) => {
  if (e && e.length > 0) {
    form.value.start_time = dayjs(e[0]).format('YYYY-MM-DD 00:00:00')
    form.value.end_time = dayjs(e[1]).format('YYYY-MM-DD 23:59:59')
  } else {
    form.value.start_time = null
    form.value.end_time = null
  }
}

// 初始化禁用行
const initDisabledRows = (disabledVal: Record<string, any>[]) => {
  if (disabledVal?.length) {
    disabledRows.value = new Set(disabledVal.map((item) => item.id))
  }
}

//批量勾选
const handleSelectionChange = (val: any[]) => {
  if (val.length > 1 && !props.multiple) {
    // 如果选中的行数超过一行， 并且不允许多选，清除之前的选中项，只保留最新的选中项
    const latestSelection = val[val.length - 1]
    tableRef.value.clearSelection()
    tableRef.value.toggleRowSelection(latestSelection, true)
    multipleSelection.value = [latestSelection]
  } else {
    multipleSelection.value = val
  }
}

//点击添加按钮
// 在submit方法中添加传递商品基础信息 - 修改
const submit = () => {
  if (!multipleSelection.value.length) return ElMessage.warning('请勾选商品')

  // 构造基础商品信息
  const selectedProducts = multipleSelection.value.map((item) => ({
    id: item.id,
    cname: item.cname,
    sku: item.sku
    // 其他可能需要传递的基础信息...
  }))

  // 传递基础商品信息（不含数量）
  emit('exposeMultipleData', selectedProducts)
  closeDialog()
}

//判断数组每一项指定字段是否相同
const areIdsEqual = (array: any[], key?: string) => {
  const firstId = array[0][key ?? 'id']
  return array.every((item: Record<string, any>) => item[key ?? 'id'] === firstId)
}

//一维数组去重
const deduplication = (val: any[], key?: string) => {
  if (!val || !val.length) return
  return val.reduce((acc, item) => {
    if (!acc.some((x: Record<string, any>) => x[key ?? 'id'] === item[key ?? 'id'])) {
      acc.push(item)
    }
    return acc
  }, [])
}

//点击取消关闭弹框
const closeDialog = () => {
  reset()
  dialogVisible.value = false
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getGoodsEnumApi({ field: 'all' })
  brandList.value = resp.data.brand
  modelList.value = resp.data.model
  algorithmList.value = resp.data.algorithm
}

//初始化请求
const getList = async () => {
  tableLoading.value = true
  const params = JSON.parse(JSON.stringify(form.value))
  delete params.date
  const resp = await getListApi(params)
  dataList.value = resp.data.list
  paginationTotal.value = resp.data.total
  // paginationTotal.value = 5
  tableLoading.value = false
}

//重置查询项
const reset = (isRequest?: boolean) => {
  form.value = {
    cname: '',
    abbr: '',
    brand: '',
    type: '',
    algorithm: '',
    model: '',
    pageIndex: 1,
    pageSize: 15
  }
  isReset.value = false
  paginationTotal.value = 0
  multipleSelection.value = []
  nextTick(() => {
    tableRef!.value!.clearSelection()
  })
  if (isRequest) {
    getList()
    isReset.value = true
  }
}

const initialize = (selectionVal: any[], disabledVal?: any[]) => {
  getDropDownBoxInfo()
  getList()

  if (disabledVal && disabledVal.length) {
    // 初始化禁用行
    initDisabledRows(disabledVal)
  }

  selectionPak.value = selectionVal
  if (!selectionVal || !selectionVal.length) return
  selectionVal.forEach((item: Record<string, any>) => {
    nextTick(() => {
      tableRef!.value!.toggleRowSelection(item, true)
    })
  })
}

defineExpose({
  dialogVisible,
  initialize
})
</script>

<style lang="less" scoped></style>
